package com.outfood.api.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.outfood.common.common.CurrentUser;
import com.outfood.common.common.replay.ReplyCode;
import com.outfood.common.common.response.CommonPage;
import com.outfood.common.common.response.RestResponse;
import com.outfood.config.PythonServerConfig;
import com.outfood.config.WxConfig;
import com.outfood.domain.Store;
import com.outfood.service.IStoreService;
import com.outfood.service.impl.SeleniumServiceImpl;
import com.outfood.vo.DownInfo;
import com.ruoyi.common.exception.BusinessException;
import com.rys.common.core.controller.BaseController;
import com.rys.common.utils.DateUtils;
import com.rys.common.utils.StringUtils;
import com.tps.open.mq.MqService;
import com.tps.open.mq.enums.QueueEnums;
import com.tps.open.mq.model.MessageBody;
import com.tps.open.oss.UploadService;
import com.tps.open.weixin.dto.TemplateDTO;
import com.tps.open.weixin.dto.TemplateValue;
import com.tps.open.weixin.vo.XcxPayPramsVO;
import io.swagger.annotations.*;
import lombok.Data;
import org.apache.dubbo.config.annotation.Reference;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;

/**
 * @Author huisonglin
 * @Description
 * @PackageName outfood-platform
 * @Package com.outfood.api.controller
 * @Date 2024-03-26 11:52
 * @Version 1.0
 */
@RestController
@Api(value = "RepairRecordController" ,tags = {"店铺操作类"})
@RequestMapping("/api/store")
public class StoreController extends BaseController {

    @Resource
    IStoreService storeService;


    @Data
    @ApiModel("通过账户密码登录")
    public class AddByPassword{

        @ApiModelProperty("用户名")
        private String username;
        @ApiModelProperty("密码")
        private String password;

    }

    @Resource
    WxConfig wxConfig;
    @Reference
    MqService mqService;
    @Reference
    UploadService uploadService;


    @Resource
    RedisTemplate redisTemplate;

    @Resource
    PythonServerConfig pythonServerConfig;
    @ApiOperation("饿了么二维码登录")
    @GetMapping("/loginByQrCode")
    public RestResponse loginByQrCode(){
        String qrCode = (String) redisTemplate.opsForValue().get(SeleniumServiceImpl.QRCODEFLAG);
        if(StringUtils.isBlank(qrCode)){
            SeleniumServiceImpl SeleniumService = new SeleniumServiceImpl();
             qrCode = SeleniumService.getQrCode(CurrentUser.getUserId(), uploadService, storeService,redisTemplate);
        }
        QRcode qRcode = new QRcode();
        qRcode.setUrl(qrCode);
        return RestResponse.success(qRcode);
    }
    @Resource
    RestTemplate restTemplate;
    @ApiOperation("饿了么账号密码登录")
    @GetMapping("/elemePassword")
    public RestResponse<SeleniumServiceImpl.CodeLoginResult> elemePassword(@ApiParam("用户名")@RequestParam String username,@ApiParam("密码")@RequestParam  String password){
        SeleniumServiceImpl seleniumService = new SeleniumServiceImpl();
        SeleniumServiceImpl.CodeLoginResult codeLoginResult = seleniumService.elemePassword(username, password, CurrentUser.getUserId(), storeService, redisTemplate);
        return RestResponse.success(codeLoginResult);


    }

    public static void main(String[] args) {
        String cookie = "[{\"domain\":\".ele.me\",\"expiry\":1733834030000,\"httpOnly\":false,\"name\":\"tfstk\",\"path\":\"/\",\"secure\":false,\"value\":\"f39-vy4QOq0l9ucHF3GDxTc1nDnmwLKy0U-_KwbuOELvoFBhr2PkMwTyuwfI4e2pMEYOP0WhKEQBzE7hP_1ShrsPj7sCO6TvJHL6ZMDrUH1BleRuEaAk9yBynQ2hr4WpAFXKSVDiI3-PT9giStg90bXCAvbILzcSB9WISqXdenk5LFxHogGpcmIhxW_BRgMjDMjQV9_5OrNffZ_Cd9TClZs1X7s5d8_fGbFqJZZ5-JdpGqfNI0CTdJ9jL_Q9VW2QdKIRwpt5kuZWHgCRWsvN79vWoH9kUsl4i9-D6edB5qVlPCI9k1A-W8L9zMTAEdiEas5BppI2g2FdWBtk_B1xVYtAeaCBnEZggTdBzpCywkowcTT2_N5SgqSvEdfd7sUjPnxAP1dprqyCrCKXk1v0oRX6_Epd1OsrRdvTOf4GWMVSDmFUT_sclSTm7V2OkUSAS0HLTW5q0JVRmiVQObSVDNmxJWPFNj5..\"},{\"domain\":\".ele.me\",\"expiry\":1718886824000,\"httpOnly\":false,\"name\":\"x5check_napos\",\"path\":\"/\",\"secure\":false,\"value\":\"ZJYZMTMTA1MzE4MDQ5OTE1MjAxUFRmSTI5STZQ\"},{\"domain\":\".ele.me\",\"expiry\":1718886831000,\"httpOnly\":false,\"name\":\"ksid\",\"path\":\"/\",\"secure\":false,\"value\":\"ZJYZMTMTA1MzE4MDQ5OTE1MjAxUFRmSTI5STZQ\"},{\"domain\":\"napos-order-pc.faas.ele.me\",\"expiry\":1733834033000,\"httpOnly\":false,\"name\":\"arms_uid\",\"path\":\"/app/processing\",\"secure\":false,\"value\":\"d97d5576-5fd8-4aed-8058-6bbcfea33891\"},{\"domain\":\".ele.me\",\"httpOnly\":false,\"name\":\"AEM_TAG_ID_CATCH_DATA_ES00000021\",\"path\":\"/\",\"secure\":false,\"value\":\"{%22tagId%22:%22ES00000021%22%2C%22data%22:%22%E5%9F%8E%E5%B8%82%E5%8D%95%E5%BA%97%22%2C%22userId%22:1197865222%2C%22time%22:1718282032257}\"},{\"domain\":\".ele.me\",\"httpOnly\":false,\"name\":\"AEM_TAG_ID_CATCH_DATA_ES00000044\",\"path\":\"/\",\"secure\":false,\"value\":\"{%22tagId%22:%22ES00000044%22%2C%22data%22:%22%E5%BF%AB%E9%A4%90%E4%BE%BF%E5%BD%93%22%2C%22userId%22:1197865222%2C%22time%22:1718282032256}\"},{\"domain\":\".ele.me\",\"expiry\":1752842022000,\"httpOnly\":false,\"name\":\"cna\",\"path\":\"/\",\"secure\":true,\"value\":\"JdXxHi3DmxkCAXSVxkPkGhCb\"},{\"domain\":\".ele.me\",\"expiry\":1718886832000,\"httpOnly\":false,\"name\":\"jst2_t0\",\"path\":\"/\",\"secure\":false,\"value\":\"1718282032056\"},{\"domain\":\".ele.me\",\"httpOnly\":false,\"name\":\"AEM_TAG_ID_CATCH_DATA_ES00000035\",\"path\":\"/\",\"secure\":false,\"value\":\"{%22tagId%22:%22ES00000035%22%2C%22userId%22:1197865222%2C%22time%22:1718282032257}\"},{\"domain\":\".ele.me\",\"httpOnly\":false,\"name\":\"AEM_TAG_ID_CATCH_DATA_ES00000069\",\"path\":\"/\",\"secure\":false,\"value\":\"{%22tagId%22:%22ES00000069%22%2C%22data%22:%22%E8%80%81%E5%BA%97%22%2C%22userId%22:1197865222%2C%22time%22:1718282032257}\"},{\"domain\":\".ele.me\",\"expiry\":1718886831000,\"httpOnly\":false,\"name\":\"shopId\",\"path\":\"/\",\"secure\":false,\"value\":\"1197865222\"},{\"domain\":\".ele.me\",\"expiry\":1733834037000,\"httpOnly\":false,\"name\":\"isg\",\"path\":\"/\",\"secure\":true,\"value\":\"BA8PUtzwtWwKjbGQ9mqopMmrnqMZNGNW7HK0gyEcpn6F8C3yPABDp_dw9CDOkzvO\"},{\"domain\":\".ele.me\",\"httpOnly\":false,\"name\":\"AEM_TAG_ID_CATCH_DATA_ES00000019\",\"path\":\"/\",\"secure\":false,\"value\":\"{%22tagId%22:%22ES00000019%22%2C%22data%22:%22%E6%9D%AD%E5%B7%9E%22%2C%22userId%22:1197865222%2C%22time%22:1718282032257}\"},{\"domain\":\".ele.me\",\"expiry\":1718541222000,\"httpOnly\":false,\"name\":\"xlly_s\",\"path\":\"/\",\"secure\":true,\"value\":\"1\"}]";
        List<Cookie> cookies = JSON.parseArray(cookie, Cookie.class);
        Set<Object> objects = new HashSet<>(cookies);
        System.out.println(objects);

    }



    @ApiOperation("饿了么手机号登录")
    @GetMapping("/elemePhoneLogin")
    public RestResponse elemePhoneLogin(@ApiParam("手机号")@RequestParam String moible){
        SeleniumServiceImpl seleniumService = new SeleniumServiceImpl();
        seleniumService.elemePhoneLogin(moible,storeService,CurrentUser.getUserId(),redisTemplate);
        return new RestResponse(ReplyCode.SYS.SUCCESS,"发送成功");

    }



    @ApiOperation("账号密码登录通过code")
    @GetMapping("/elemepasswordSendCode")
    public RestResponse<SeleniumServiceImpl.CodeLoginResult> elemepasswordSendCode(@ApiParam("账号密码登录")@RequestParam  String code) throws InterruptedException {
        redisTemplate.delete(SeleniumServiceImpl.CODEINFO + CurrentUser.getUserId());
        redisTemplate.opsForValue().set(CurrentUser.getUserId()+"code",code);
        Long endTime = new Date().getTime()+1000*20;
        SeleniumServiceImpl.CodeLoginResult result = null;
        while(new Date().getTime() < endTime){
            logger.info("正在尝试获取登录结果");
            Thread.sleep(500);
            result  = (SeleniumServiceImpl.CodeLoginResult) redisTemplate.opsForValue().get(SeleniumServiceImpl.CODEINFO + CurrentUser.getUserId());
            if(result != null){
                break;
            }

        }
        if(result == null){
            throw new BusinessException("系统开小差了请重新登录");
        }

        return RestResponse.success(result);
    }

    @Data
    public static class QRcode{
        private String url;
    }

    @ApiOperation("消息订阅测试")
    @GetMapping("/dingyue")
    public  RestResponse dy(){
        MessageBody messageBody = new MessageBody();
        messageBody.setHandlerBeanName("templateComsumerHandler");
        TemplateDTO templateDTO = new TemplateDTO();
        templateDTO.setTemplate_id("Z704ZWJ5VAstDdlD7Akc3wZlJh9udPnQbiiRudk0V1c");
        templateDTO.setTouser("oGv4x4z5eGB4Fwd_plHhB1bXyTLk");
        Map<String, TemplateValue> data = new HashMap<>();
        data.put("thing1", new TemplateValue("沙县小吃 合肥店"));
        data.put("phrase2", new TemplateValue("掉线"));
        data.put("time3", new TemplateValue(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",new Date())));
        templateDTO.setPage("/pages/relogin/relogin?storeId=3");
        templateDTO.setData(data);
        templateDTO.setAppid(wxConfig.getWxAppid());
        templateDTO.setSecret(wxConfig.getWxSecret());
        messageBody.setBody(JSON.toJSONString(templateDTO));
        mqService.send(messageBody, QueueEnums.WEIXIN_ADMIN);
        return new RestResponse(ReplyCode.SYS.SUCCESS,"操作成功");
    }
    @ApiOperation("消息订阅测试2")
    @GetMapping("/sends")
    public void dingyue2(){
        MessageBody messageBody = new MessageBody();
        messageBody.setHandlerBeanName("upNoticeComsumerHander");
        DownInfo downInfo = new DownInfo();
        downInfo.setStoreId(55L);
        messageBody.setBody(JSON.toJSONString(downInfo));
        mqService.send(messageBody,QueueEnums.OUTFOOD_ADMIN);
    }

    @ApiOperation("根据门店ID获取门店账号信息")
    @GetMapping("/getStoreInfo")
    public RestResponse<StoreInfo> getStoreInfo(@ApiParam("门店ID")@RequestParam  Long storeId){
        Store store = storeService.get(storeId);
        StoreInfo storeInfo = new StoreInfo();
        storeInfo.setMobile(store.getMobile());
        storeInfo.setUsername(store.getUsername());
        storeInfo.setPassword(store.getPassword());
        return RestResponse.success(storeInfo);

    }
    @Data
    @ApiModel("门店账户信息参数")
    public static class StoreInfo{
        @ApiModelProperty("手机号")
        private String mobile;
        @ApiModelProperty("用户名")
        private String username;
        @ApiModelProperty("密码")
        private String password;
    }


    @ApiOperation("通过账户密码添加")
    @GetMapping("/addBypassword")
    public RestResponse addBypassword(AddByPassword addByPassword){
        Store store = storeService.addBypassword(addByPassword.getUsername(), addByPassword.getPassword(), CurrentUser.getUserId());
        return new RestResponse(ReplyCode.SYS.SUCCESS,"操作成功");
    }

    @ApiOperation("门店续费")
    @GetMapping("/renew")
    public RestResponse<XcxPayPramsVO> renew(@ApiParam("门店ID")@RequestParam Long storeId,
                                             @ApiParam("月份")@RequestParam Integer month,@ApiParam("价格")@RequestParam String price){
        XcxPayPramsVO renew = storeService.renew(storeId, month, CurrentUser.getUserId(),price);
        return RestResponse.success(renew);
    }
        
    @ApiOperation("添加测试门店仅供小程序上架审核使用")
    @GetMapping("/addTestStore")
    public RestResponse addTestStore(String storeName){
        storeService.addTestStore(storeName,CurrentUser.getUserId());
        return new RestResponse(ReplyCode.SYS.SUCCESS,"操作成功");
    }

    @ApiOperation("发送验证码")
    @GetMapping("/sendCode")
    public RestResponse sendCode(@ApiParam("手机号")@RequestParam  String mobile){
        storeService.sendCode(mobile);
        return new RestResponse(ReplyCode.SYS.SUCCESS,"操作成功");
    }

    @ApiOperation("验证码登录")
    @GetMapping("/loginByCode")
    public RestResponse loginByCode(@ApiParam("手机号")@RequestParam String mobile,@ApiParam("验证码")@RequestParam  String code){
        SeleniumServiceImpl.CodeLoginResult codeLoginResult = new SeleniumServiceImpl.CodeLoginResult();
        try {
            storeService.loginByCode(mobile,code,CurrentUser.getUserId());
        } catch (Exception e) {
            if("首次验证".equals(e.getMessage())){

                codeLoginResult.setCode("1001");
                codeLoginResult.setMessage("需要解除首次登录");
                logger.error(e.getMessage());
                return new RestResponse(codeLoginResult); //需要首次验证
            }else{
                throw e;
            }
        }
        codeLoginResult.setCode("0");
        codeLoginResult.setMessage("登录成功");
        return new RestResponse(codeLoginResult);
    }

    @ApiOperation("通过Cookie绑定")
    @GetMapping("/loginByCookie")
    public RestResponse loginByCookie(@ApiParam("cookie")@RequestParam String cookie){
        Store store = storeService.loginByCookie(cookie, CurrentUser.getUserId());
        return new RestResponse(ReplyCode.SYS.SUCCESS,"操作成功");
    }

    @ApiOperation("通过Cookie重新登录")
    @GetMapping("/reloginByCookie")
    public RestResponse reloginByCookie(@ApiParam("cookie")@RequestParam  String cookie,@ApiParam("店铺ID")@RequestParam  Long storeId){
        Store store = storeService.reloginByCookie(cookie, CurrentUser.getUserId(), storeId);
        return new RestResponse(ReplyCode.SYS.SUCCESS,"操作成功");
    }

    @ApiOperation("通过账号密码重新登录")
    @GetMapping("/reloginBypassword")
    public RestResponse reloginBypassword(@ApiParam("用户名")@RequestParam String username,
                                          @ApiParam("密码")@RequestParam String password,
                                          @ApiParam("门店ID")@RequestParam  Long storeId){
        storeService.reloginBypassword(username,password,CurrentUser.getUserId(),storeId);
        return new RestResponse(ReplyCode.SYS.SUCCESS,"操作成功");
    }

    @ApiOperation("通过验证码重新登录")
    @GetMapping("/reloginByCode")
    public RestResponse reloginByCode(@ApiParam("手机号")@RequestParam String mobile,
                                      @ApiParam("验证码")@RequestParam
                                              String code,
                                      @ApiParam("门店ID")@RequestParam Long storeId){
        storeService.reloginByCode(mobile,code,CurrentUser.getUserId(),storeId);
        return new RestResponse(ReplyCode.SYS.SUCCESS,"操作成功");
    }

    @ApiOperation("获取门店列表")
    @GetMapping("/storeList")
    public RestResponse<CommonPage<StoreVO>> getStoreList(@ApiParam("页号")@RequestParam Integer pageNum, @ApiParam("每页条数")@RequestParam(defaultValue = "10") Integer pageSize,@ApiParam("门店状态 ONLINE 在线 OFF 离线") String onlineStatus,@ApiParam("是否过期 1没有过期 2过期了") String storeStatus){
        startPage();
        List<Store> storeList = storeService.getStoreList(CurrentUser.getUserId(),onlineStatus,storeStatus);
        CommonPage optiontPreeCommonPage = CommonPage.restPage(storeList);
        List<StoreVO> repairRecordVOS = new ArrayList<>();
        storeList.forEach(store -> {
            StoreVO storeVO = new StoreVO();
            BeanUtils.copyProperties(store,storeVO);
            if("TRUE".equals(store.getAutoReplay())){
                storeVO.setDisAutoReplay(true);
            }else{
                storeVO.setDisAutoReplay(false);
            }
            if("FALSE".equals(store.getAutoOut())){
                storeVO.setDisAutoOut(false);
            }else{
                storeVO.setDisAutoOut(true);
            }
            repairRecordVOS.add(storeVO);
        });
        optiontPreeCommonPage.setRows(repairRecordVOS);
        return RestResponse.toPageData(optiontPreeCommonPage);
    }


//    @ApiOperation("饿了么账号密码登录")
//    @GetMapping("/loginByEleme")
//    public RestResponse loginByEleme(@ApiParam("用户名")@RequestParam String username,@ApiParam("密码")@RequestParam String password){
//        storeService.loginByEleme(username,password,CurrentUser.getUserId());
//        return new RestResponse(ReplyCode.SYS.SUCCESS,"操作成功");
//    }
//
//    @ApiOperation("饿了么验证码登录")
//    @GetMapping("/loginByCodeEleme")
//    public RestResponse loginByCode(@ApiParam("验证码")@RequestParam String code,
//                                    @ApiParam("用户名")@RequestParam String username,
//                                    @ApiParam("密码")@RequestParam String password){
//        storeService.loginByCode(code,CurrentUser.getUserId(),username,password);
//        return new RestResponse(ReplyCode.SYS.SUCCESS,"操作成功");
//    }


    @ApiOperation("设置自动出餐权限")
    @GetMapping("outSet")
    public RestResponse evaluateSet(@ApiParam("门店ID")@RequestParam Long storeId, String  autoOut){
        Store store = new Store();
        store.setId(storeId);
        store.setAutoOut(autoOut);
        storeService.update(storeId,store, CurrentUser.getUserId()+"");
        return new RestResponse<>(ReplyCode.SYS.SUCCESS,"操作成功");

    }

    @Data
    @ApiModel("门店列表返回参数")
    public static class StoreVO{
        /**
         * 主键ID
         */
        @ApiModelProperty("主键")
        private Long id;

        /**
         * 手机号
         */
        private String mobile;


        /**
         * 过期时间
         */
        @JsonFormat(pattern = "yyyy-MM-dd")
        private Date expireTime;



        private Integer time;


        private Boolean disAutoReplay;


        private Boolean disAutoOut;

        /**
         * 在线状态
         */
        @ApiModelProperty("在线状态")
        private String onlineStatus;


        private String storeStatus;


        /**
         * 自动回复评价功能
         */
        private String autoReplay;

        /**
         * 商家名称
         */
        @ApiModelProperty("商家名称")
        private String storeName;




        /**
         * MEITUAN  、  ELME
         */
        private String platform;





        /**
         * create_date
         */
        private Date createDate;


    }

}
